<template>
  <div class="statisticsPage h100" style="overflow-y:auto">
    <!-- 任务统计 -->
    <div class="statististatisticsEchartWrap">
      <div class="statisticsEchartTop" ref="statisticsEchartTop">
        <!-- <h2 class="title18">{{ $t('statisticsOfCampaign') }}</h2> -->
        <div class="statisticsEchartTopSearch table-page-search-wrapper" ref="statisticsEchartTopSearch">
          <task-select
            :time="taskSelectTime"
            @changeoption="changeTask($event, 'taskIds')"
            :default-task-id="queryParams.taskIds"
            :query="{ type: [queryParams.taskType, 2] }"
            style="width: 300px;"
            :readonly="isOneTaskDetail"
            :clear="true"
            mode="multiple"
          ></task-select>
          <a-range-picker
            @change="onRangeChange"
            :value="defaultDateRange"
            :disabled-date="disabledDate"
            :allow-clear="false"
            style="margin-left: 10px; width: 240px"
          />
          <a-button-group style="margin:0 10px">
            <auth-button type="primary" :auth="statisticsPerms.task.view" @click="searchData">
              <i class="iconfont icon-chazhao"></i>
              {{ $t('inquiry') }}
            </auth-button>
            <a-button @click="clearCondition">
              <i class="iconfont icon-qingkong"></i>
              {{ $t('clear') }}
            </a-button>
          </a-button-group>
          <auth-button
            type="primary"
            :loading="exporting"
            :auth="statisticsPerms.task.export"
            @click="exportStatisticsTask"
          >
            <i class="iconfont icon-xiazai"></i>
            {{ $t('export') }}
          </auth-button>
        </div>
      </div>
      <div class="statisticsEchartMain">
        <loading-state :echartShowStatus="echartShowStatus" class="chartMain">
          <div ref="chartDom" style="height: 100%" v-show="echartShowStatus === 2"></div>
        </loading-state>
      </div>
    </div>
    <!-- 详细列表 -->
    <div class="statisticsTableWrap">
      <div class="statisticsTableTop">
        <h2 class="title18">{{ $t('detailList') }}({{ taskTotal }})</h2>
        <a-button type="info" v-show="isOneTaskDetail" @click="goBack">{{ $t('back') }}</a-button>
      </div>
      <div class="h100 commonTableSty statisticsTableBox">
        <el-table
          ref="tableRef"
          :data="tbData"
          border
          show-summary
          :summary-method="getSummaries"
          height="90%"
          @sort-change="sortChange"
        >
          <el-table-column v-if="!isOneTaskDetail" prop="taskName" :label="$t('campaignName')" min-width="100">
          </el-table-column>
          <el-table-column v-if="isOneTaskDetail" prop="date" :label="$t('date')" sortable="custom"> </el-table-column>
          <el-table-column prop="checkSuccessCount" :label="$t('jccgs')" sortable="custom" min-width="120">
          </el-table-column>
          <el-table-column prop="downloadSuccessCount" :label="$t('xzcgs')" sortable="custom" min-width="120">
          </el-table-column>
          <el-table-column prop="upgradeSuccessCount" :label="$t('sjcgs')" sortable="custom" min-width="120">
          </el-table-column>
          <el-table-column v-if="!isOneTaskDetail" :label="$t('upgradeVehicle')">
            <template slot-scope="scope">
              <a-tooltip
                :title="
                  $t('ysjclzbs') +
                    ': ' + (scope.row.taskVehicleCount == 0 ? '-' : ((scope.row.upgradeSuccessCount/ scope.row.taskVehicleCount).toFixed(2) * 100)+'%')
                "
              >
                <div class="sjclBox">
                  <span class="sjclNumber">
                    <table-ellipsis
                      :text="scope.row.upgradeSuccessCount + '/' + scope.row.taskVehicleCount"
                    ></table-ellipsis>
                  </span>
                  <a-progress
                    :percent="(scope.row.upgradeSuccessCount / scope.row.taskVehicleCount).toFixed(2) * 100"
                    :showInfo="false"
                    class="sjclProgress"
                    size="small"
                  />
                </div>
              </a-tooltip>
            </template>
          </el-table-column>
          <el-table-column
            v-if="!isOneTaskDetail"
            :label="$t('timeOfCreation')"
            prop="createTime"
            min-width="100"
            :default-sort="{ order: 'descending' }"
            sortable
          >
            <template slot-scope="scope">
              {{ $commonFun.getDateTimeStr(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column v-if="!isOneTaskDetail" :label="$t('rwyxq')" min-width="130">
            <template slot-scope="scope">
              {{scope.row.startTime&&scope.row.endTime?
                `${$commonFun.getDateMinuteStr(scope.row.startTime)}~${$commonFun.getDateMinuteStr(scope.row.endTime)}`:'-'
              }}
            </template>
          </el-table-column>
          <el-table-column v-if="!isOneTaskDetail" :label="$t('operation')" width="100">
            <template slot-scope="scope">
              <i class="iconfont icon-riqi" @click="statisticsOneTask(scope.row)"></i>
              <i class="iconfont icon-tongji tongji" @click="showOneTaskChart(scope.row)" v-show="false"></i>
            </template>
          </el-table-column>
          <template slot="empty">
            <loading-state :outsidePosition="true" style="position: unset;" :echartShowStatus="3"></loading-state>
          </template>
        </el-table>
      </div>
    </div>
  </div>
</template>
<script>
import TaskSelect from '@/views/components/TaskSelect'
import { mapState } from 'vuex'
import { kLineTaskOption } from '../config/chart'
import TableEllipsis from '@/components/Ellipsis/TableEllipsis'
import OneTaskChart from './components/OneTaskChart'
import lodash from 'lodash'
import moment from 'moment'
import statisticsApi from '@/api/modules/statistics'
import { STable } from '@/components'
import { downloadBlobFile } from '@/utils/functions'
import AuthButton from '@/components/AuthButton'
import { statisticsPerms } from '@/config/permission/index'
export default {
  components: {
    TaskSelect,
    TableEllipsis,
    OneTaskChart,
    STable,
    AuthButton,
  },
  computed: {
    ...mapState({
      queryParams: (state) => state.statisticsTask.queryParams,
      taskStatusIcon: (state) => state.dict.taskUpdateStateObj
    }),
    // 日期选择的默认值
    defaultDateRange () {
      if (this.queryParams.startTime && this.queryParams.endTime) {
        return [moment(this.queryParams.startTime), moment(this.queryParams.endTime)]
      }
      return []
    },
    taskUpdateDictCodeObj () {
      return this.$store.getters.getDictCodeObj('taskUpdateDictCode')
    },
    isOneTaskDetail () {
      return Boolean(this.$route.query.t)
    }
  },
  data () {
    const _this = this
    return {
      statisticsPerms,
      taskSelectTime: 12344321,
      // 获取图表数据状态
      echartShowStatus: -1,
      // 详细列表数据
      tbData: [],
      // 是否在加载详细列表
      loadingTbData: false,
      // 图表的配置
      chartOption: lodash.cloneDeep(kLineTaskOption),
      // 图表实例化对象
      chart: null,
      taskTotal: 0,
      // 排序列信息
      sortedInfo: null,
      exporting: false,
      chartConfig: {
        11: {
          title: _this.$t('jccgs')
        },
        21: {
          title: _this.$t('xzcgs')
        },
        100: {
          title: _this.$t('sjcgs')
        }
      },
      // 排序
      order: ''
    }
  },
  watch: {
    isOneTaskDetail: {
      handler () {
        this.order = ''
        this.sortedInfo = null
      }
    }
  },
  created () {
    this.getPageDictData()
    this.initQuery(this.$route.query)
  },
  updated () {
    this.$nextTick(() => {
      this.$refs.tableRef.doLayout()
    })
  },
  methods: {
    initQuery (val) {
      let taskId = ''
      if (val && val.t) {
        taskId = val.t
      }
      if (val.startTime && val.endTime) {
        this.queryParams.startTime = moment(val.startTime * 1).format('YYYY-MM-DD')
        this.queryParams.endTime = moment(val.endTime * 1).format('YYYY-MM-DD')
      }
      if (taskId) {
        this.queryParams.taskIds = [taskId]
        this.initPageDataOneTask()
      } else {
        this.initPageDataAllTask()
      }
    },
    sortChange ({ prop, order }) {
      const orderType = {
        ascending: 'ASC',
        descending: 'DESC'
      }
      this.order = ''
      if (order && prop) {
        this.order = `${prop},${orderType[order]}`
      }
      this.searchData()
    },
    getSummaries (param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = this.$t('footing')
          return
        }
        const values = data.map((item) => Number(item[column.property]))
        const summaryColum =
          column.property === 'checkSuccessCount' ||
          column.property === 'downloadSuccessCount' ||
          column.property === 'upgradeSuccessCount'
        if (summaryColum && !values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            }
            return prev
          }, 0)
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    clearCondition () {
      this.$store.commit('resetStatisticsTaskQueryParams')
      if (this.isOneTaskDetail) {
        this.queryParams.taskIds = [this.$route.query.t]
        this.initPageDataOneTask()
      } else {
        this.initPageDataAllTask()
      }
    },
    // 获取非单个任务的页面数据
    initPageDataAllTask () {
      this.getStatisticsTaskEchartData()
      this.getStatisticsTaskTableData()
    },
    // 获取单个项目的页面数据
    initPageDataOneTask () {
      this.getStatisticsTaskEchartData()
      this.loadOneTaskTbData()
    },
    searchData () {
      if (this.isOneTaskDetail) {
        this.initPageDataOneTask()
      } else {
        this.initPageDataAllTask()
      }
    },
    // 获取任务统计的图表数据 isOneTaskDetail是否是查看某个任务的详情，是的话列表数据就是图表请求回来的数据只是要处理下
    getStatisticsTaskEchartData () {
      this.echartShowStatus = 1
      const params = {
        ...this.queryParams
      }
      statisticsApi
        .getTaskReportChartData(params)
        .then((res) => {
          const { data } = res
          if (!data) {
            this.echartShowStatus = 3
            return
          }
          let yAxisMax1 = -1
          let yAxisMin1 = 99999
          const series = []
          const legendData = []
          Object.keys(data.yaxisData).forEach((key, index) => {
            const name = this.chartConfig[key].title
            const obj = {
              name,
              data: data.yaxisData[key],
              type: 'line',
              smooth: true
            }
            const itemMaxData = Math.max(...data.yaxisData[key])
            const itemMinData = Math.min(...data.yaxisData[key])
            if (itemMaxData > yAxisMax1) {
              yAxisMax1 = itemMaxData
            }
            if (itemMinData < yAxisMin1) {
              yAxisMin1 = itemMinData
            }
            if (index % 2 === 0) {
              obj.yAxisIndex = 1
            }
            series.push(obj)
            legendData.push(name)
          })
          this.chartOption.series = series
          this.chartOption.xAxis[0].data = data.xaxisData.map((item) => {
            return moment(item).format('MM-DD')
          })
          this.chartOption.legend.data = legendData
          const splitNumber = 4
          this.chartOption.yAxis[0].interval = Math.ceil(yAxisMax1 / splitNumber)
          this.chartOption.yAxis[0].max = this.chartOption.yAxis[0].interval * splitNumber
          this.chartOption.yAxis[1].interval = this.chartOption.yAxis[0].interval
          this.chartOption.yAxis[1].max = this.chartOption.yAxis[0].max
          this.echartShowStatus = 2
          this.$nextTick(() => {
            this.initChartBox()
            this.setOption()
            this.bindEvent()
          })
        })
        .catch(() => {
          this.echartShowStatus = 3
        })
    },
    // 获取任务详细列表的表格数据
    getStatisticsTaskTableData () {
      this.loadingTbData = true
      this.restTbData()
      const params = {
        ...this.queryParams
      }
      if (this.order) {
        params.order = this.order
      }
      statisticsApi
        .getTaskReportListData(params)
        .then((res) => {
          const data = res.data.map((item) => {
            return {
              taskId: item.taskId,
              taskName: item.taskName,
              status: item.status,
              checkSuccessCount: item.checkSuccessCount || 0,
              downloadSuccessCount: item.downloadSuccessCount || 0,
              upgradeSuccessCount: item.upgradeSuccessCount || 0,
              taskVehicleCount: item.taskVehicleCount,
              startTime: item.startTime,
              endTime: item.endTime,
              createTime: item.createTime
            }
          })
          this.taskTotal = data.length
          this.tbData = data
        })
        .finally(() => {
          this.loadingTbData = false
        })
    },
    getStatisticsOneTaskTableData (data) {
      const arr = []
      data.forEach((item) => {
        const obj = {
          date: item.date,
          checkSuccessCount: item.checkSuccessCount,
          downloadSuccessCount: item.downloadSuccessCount,
          upgradeSuccessCount: item.upgradeSuccessCount
        }
        arr.push(obj)
      })
      this.taskTotal = arr.length
      this.tbData = arr
      this.loadingTbData = false
    },
    restTbData () {
      this.tbData = []
      this.taskTotal = 0
    },
    changeTask (val) {
      this.queryParams.taskIds = val
    },
    onRangeChange (date, dateString) {
      if (date.length === 0) {
        this.queryParams.startTime = moment().subtract(1, 'months').format('YYYY-MM-DD')
        this.queryParams.endTime = moment().endOf('day').format('YYYY-MM-DD')
        return
      }
      const maxDays = 365
      if (date[1].diff(date[0], 'days') > maxDays) {
        this.$message.error(this.$t('dateRangeTip').replace('__DAYS__', maxDays))
        // eslint-disable-next-line prefer-destructuring
        this.queryParams.startTime = dateString[0]
        this.queryParams.endTime = moment(dateString[0]).add(maxDays, 'days').format('YYYY-MM-DD')
        // eslint-disable-next-line consistent-return
        return false
      }
      // eslint-disable-next-line prefer-destructuring
      this.queryParams.startTime = dateString[0]
      // eslint-disable-next-line prefer-destructuring
      this.queryParams.endTime = dateString[1]
    },
    // 时间限制范围 结束时间不能超过今天
    disabledDate (current) {
      return current > moment()
    },
    getCalendarContainer () {
      return this.$refs.statisticsEchartTopSearch
    },
    initChartBox () {
      if (this.chart) {
        return
      }
      this.chart = this.$echarts.init(this.$refs.chartDom)
    },
    setOption () {
      if (!this.chart) {
        return
      }
      this.chart.setOption(this.chartOption)
    },
    bindEvent () {
      window.addEventListener('resize', this.resizeChart)
    },
    resizeChart () {
      this.chart && this.chart.resize()
    },
    // 查看某一个任务的时候
    statisticsOneTask (record) {
      this.$router.replace({
        path: '/statistics/task',
        query: {
          t: record.taskId,
          endTime: record.endTime,
          startTime: record.startTime
        }
      })
    },
    // 显示某个任务图表框
    showOneTaskChart () {},
    // 返回
    goBack () {
      this.queryParams.taskIds = []
      this.$router.replace({
        path: '/statistics/task'
      })
    },
    // 导出
    exportStatisticsTask () {
      this.exporting = true
      statisticsApi
        .getTaskReport({ ...this.queryParams })
        .then((res) => {
          downloadBlobFile(res, 'task-statistics.xlsx')
        })
        .finally(() => {
          this.exporting = false
        })
    },
    // 获取一个任务下的表格数据
    loadOneTaskTbData () {
      const params = {
        ...this.queryParams
      }
      if (this.order) {
        params.order = this.order
      }
      this.loadingTbData = true
      this.restTbData()
      statisticsApi
        .getOneTaskReportListData(params)
        .then((res) => {
          const { data } = res
          this.getStatisticsOneTaskTableData(data)
        })
        .catch(() => {
          this.loadingTbData = false
        })
    },
    getPageDictData () {
      ;['getTaskUpdateDictCodeData'].forEach((method) => {
        this.$store.dispatch(method)
      })
    }
  },
  beforeDestroy () {
    this.$store.commit('resetStatisticsTaskQueryParams')
  }
}
</script>
<style lang="less" scoped>
@import url('../style/projectTask');
.statisticsTableBox {
  flex: 1 0 0;
  .tongji {
    font-size: 22px;
    vertical-align: top;
    margin-left: 10px;
  }
  .sjclBox {
    display: flex;
  }
  .sjclNumber {
    flex: 1 0 0;
  }
  .sjclProgress {
    width: 50%;
    flex: none;
  }
}
</style>
<style lang="less">
.statisticsTableBox {
  .ant-table-placeholder {
    border-bottom: none;
  }
}
// 重写右侧框样式
.statisticsTaskRightDrawer {
  .newSideWarp {
    .content {
      padding: 0;
      .title {
        padding-top: 24px;
        padding-left: 24px;
        margin-bottom: 10px;
      }
      .btnButtonBox {
        padding: 24px;
        text-align: left;
      }
    }
  }
}
.statisticsEchartTopSearch {
  .disabledAuthButtonWrap:nth-last-child(1) {
    margin-right: 0;
  }
}
</style>
